package com.example.leetcode.high;

public class Solution1 {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 4, 5};
        int[] output = new Solution1().productExceptSelf(nums);
        for (int num : output) {
            System.out.print(num + "\t");
        }
    }

    public int[] productExceptSelf(int[] nums) {
        if (nums.length < 1) {
            return null;
        }
        int[] result = new int[nums.length];
        int[] lResult = new int[nums.length];
        int[] rResult = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int lIndex = i - 1;
            if (lIndex > -1) {
                lResult[i] = lResult[lIndex] * nums[lIndex];
            } else {
                lResult[i] = 1;
            }
        }
        for (int i = nums.length - 1; i >= 0; i--) {
            int rIndex = i + 1;
            if (rIndex < nums.length) {
                rResult[i] = rResult[rIndex] * nums[rIndex];
            } else {
                rResult[i] = 1;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            result[i] = lResult[i] * rResult[i];
        }
        return result;
    }
}
